﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using SMD = System.ServiceModel.Description;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using Dimok;

namespace CollectionInfo {
	[ScriptableType]
	public class CollectionInfoModel : Dimok.Model {

		#region Properties
		private string vantageID = "";
		public string VantageID {
			get { return vantageID; }
			set {
				vantageID = value;
				if (value + "" == "") Bridge = null;
				else LoadCollectionInfo(value);
			}
		}
		int loanID;
		public int LoanID {
			get { return loanID; }
			set { 
				loanID = value;
				RaisePropertyChanged("LoanID");
			}
		}
		MBC.Service.SLServiceClient mc;
		MBC.Service.v_Bridge _bridge;
		public MBC.Service.v_Bridge Bridge {
			get { return _bridge; }
			set {
				_bridge = value ?? new MBC.Service.v_Bridge();
				//System.Diagnostics.Debugger.Break();
				RaisePropertyChanged("Bridge", "BridgeRow");
				Settings.FirePropertyChange("ComboBox");
				if (Bridge.vantage_Payments == null) Payments.Clear();
				else {
					Payments = new ObservableCollection<MBC.Service.vantage_Payment>().Add(Bridge.vantage_Payments);
				}
				if (Bridge.vantage_Notes == null) Notes.Clear();
				else Notes = new ObservableCollection<MBC.Service.vantage_Note>().Add(Bridge.vantage_Notes);
				if (Bridge.vantage_CollateralActions == null) CollateralAction.Clear();
				else CollateralAction = new ObservableCollection<MBC.Service.vantage_CollateralAction>().Add(Bridge.vantage_CollateralActions);
				ChargeOffDetail = value == null ? new MBC.Service.vantage_ChargeOffDetail() : value.vantage_ChargeOffDetails.SingleOrDefault();
				LoanID = _bridge.LoanID.HasValue ? _bridge.LoanID.Value : 0;
			}
		}
		ObservableCollection<MBC.Service.vantage_Payment> _payments = new ObservableCollection<MBC.Service.vantage_Payment>();
		public ObservableCollection<MBC.Service.vantage_Payment> Payments {
			get { return _payments; }
			set {
				_payments = value;
				RaisePropertyChanged("Payments");
			}
		}
		ObservableCollection<MBC.Service.vantage_Note> _notes = new ObservableCollection<MBC.Service.vantage_Note>();
		public ObservableCollection<MBC.Service.vantage_Note> Notes {
			get { return _notes; }
			set {
				_notes = value;
				RaisePropertyChanged("Notes");
			}
		}
		ObservableCollection<MBC.Service.vantage_CollateralAction> _collateralAction = new ObservableCollection<MBC.Service.vantage_CollateralAction>();
		public ObservableCollection<MBC.Service.vantage_CollateralAction> CollateralAction {
			get { return _collateralAction; }
			set {
				_collateralAction = value;
				RaisePropertyChanged("CollateralAction");
			}
		}
		MBC.Service.vantage_ChargeOffDetail _chargeOffDetail;
		public MBC.Service.vantage_ChargeOffDetail ChargeOffDetail {
			get { return _chargeOffDetail ?? new MBC.Service.vantage_ChargeOffDetail(); }
			set {
				_chargeOffDetail = value;
				RaisePropertyChanged("ChargeOffDetail");
			}
		}
		public Dictionary<string, object> ChargeOffDetailRow { get { return ChargeOffDetail.ToDictionary(); } }
		public Dictionary<string, object> BridgeRow { get { return (Bridge ?? new MBC.Service.v_Bridge()).ToDictionary(); } }
		public class SettingsClass : Dimok.Model{
			public void FirePropertyChange(params string[] propertyNames) {
				RaisePropertyChanged(propertyNames);
			}
			private int _comboIndex0 = 0;
			public int ComboIndex0 {
				get { return _comboIndex0; }
				set { if (value >= 0) _comboIndex0 = value; RaisePropertyChanged("ComboIndex0"); }
			}
			private int _comboIndex1 = 0;
			public int ComboIndex1 {
				get { return _comboIndex1; }
				set { if (value >= 0)_comboIndex1 = value; RaisePropertyChanged("ComboIndex1"); }
			}
			private int _comboIndex2 = 0;
			public int ComboIndex2 {
				get { return _comboIndex2; }
				set { if (value >= 0)_comboIndex2 = value; RaisePropertyChanged("ComboIndex2"); }
			}
		}
		private SettingsClass _settings = new SettingsClass();
		public SettingsClass Settings { get { return _settings; } }
		private bool _isLoading;
		public bool IsLoading {
			get { return _isLoading; }
			private set {
				_isLoading = value;
				RaisePropertyChanged("IsLoading");
			}
		}
		private bool _isPaymentsExpanded;
		public bool IsPaymentsExpanded {
			get { return _isPaymentsExpanded; }
			private set {
				_isPaymentsExpanded = value;
				RaisePropertyChanged("IsPaymentsExpanded");
			}
		}
		private bool _isNotesExpanded;
		public bool IsNotesExpanded {
			get { return _isNotesExpanded; }
			private set {
				_isNotesExpanded = value;
				RaisePropertyChanged("IsNotesExpanded");
			}
		}
		#endregion

		#region Ctor
		public CollectionInfoModel() {
			try {
				var uri = HtmlPage.Document.DocumentUri;
				string hostUrl = uri.Scheme + "://" + uri.Host + ":" + uri.Port + "/Manager/webservices/slservice.svc";
				try {
					//string s = "BasicHttpBinding_SLService_" + (uri.Host + "" == "" ? "smallbig" : uri.Host.ToLower());
					string s = "BasicHttpBinding_ISLService";
					mc = new MBC.Service.SLServiceClient(s,new System.ServiceModel.EndpointAddress(hostUrl));
					mc.CollectionInfo_VantageCompleted += new EventHandler<MBC.Service.CollectionInfo_VantageCompletedEventArgs>(mc_CollectionInfoCompleted);
				} catch (Exception exc) {
					throw new Exception("HostUrl:" + hostUrl + Environment.NewLine + exc.Message, exc);
				}
			} catch (InvalidOperationException) {
			}

		}
		#endregion

		[ScriptableMember]
		public void LoadCollectionInfo(string VantageID){
			mc.CollectionInfo_VantageAsync(VantageID);
			IsLoading = true;
		}
		void mc_CollectionInfoCompleted(object sender, MBC.Service.CollectionInfo_VantageCompletedEventArgs e) {
			try {
				IsLoading = false;
				if (e.Error != null) throw e.Error;
				if (e.Fault != null) throw new Exception("Exception:" + e.Fault.FaultType + Environment.NewLine + e.Fault.Message);
				Bridge = e.Result;
				//mc.LoanClientPhoneAsync(e.Result.LoanClientID);
			} catch (Exception exc) {
				exc = exc.InnerException ?? exc;
				mc.ReportErrorAsync(GetMessages(exc));
				throw exc.InnerException ?? exc;
			}
		}

		string GetMessages(Exception exc) {
			List<string> m = new List<string>();
			for (; exc != null; exc = exc.InnerException)
				m.Add(exc.Message + Environment.NewLine + exc.StackTrace);
			return string.Join("".PadLeft(40, '*') + Environment.NewLine, m.ToArray());
		}



	}
	public static class Extentions {
		public static object GetProperty(this object o, string p) {
			System.Reflection.PropertyInfo pi = o.GetType().GetProperty(p);
			if (pi != null) return pi.GetValue(o, null);
			System.Reflection.FieldInfo fi = o.GetType().GetField(p);
			if (fi != null) return fi.GetValue(o);
			throw new NotImplementedException("Property/Field " + p + " is not implemented in " + o.GetType().Name + ".");
		}
		public static Dictionary<string, object> ToDictionary(this object o) {
			var d = o.GetType().GetProperties().ToDictionary(s => s.Name, s => o.GetProperty(s.Name));
			return d;
		}
	}
}
